package com.wsj.aop;

/**
 * description:
 *
 * @author yang
 * @date 2019/2/21 15:54
 */

import com.wsj.services.ProxyTest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import sun.misc.ProxyGenerator;

public class GenJdkProxyClass {

  /**
   * 生成代理类的名称
   */
  private static String DEFAULT_CLASS_NAME = "$Proxy";

  /**
   * 默认生成的文件全路径
   */
  private static String DEFAULT_FILE_PATH = DEFAULT_CLASS_NAME + ".class";


  /**
   * 使用ProxyGenerator生成代理类.class文件
   *
   * @param path 文件路径
   */
  private static void genProxyClass(String path) throws IOException {

    boolean success = new File(DEFAULT_CLASS_NAME).createNewFile();
    if (!success) {
      return;
    }
    byte[] classFile = ProxyGenerator.generateProxyClass(DEFAULT_CLASS_NAME, new Class[]{ProxyTest.class});
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(path);
      fos.write(classFile);
      fos.flush();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  public static void main(String[] args) throws IOException {
    GenJdkProxyClass.genProxyClass(DEFAULT_FILE_PATH);
  }
}